package com.link.play.fit.ai.pushWorker

import android.content.Context
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.link.play.fit.ai.ext.d
import java.util.Calendar
import java.util.concurrent.TimeUnit

class DrinkSchedulerWorker(context: Context, params: WorkerParameters) : Worker(context, params) {

    override fun doWork(): Result {
        scheduleDailyNotifications()
        return Result.success()
    }
    private fun scheduleDailyNotifications() {
        val now = System.currentTimeMillis()
        val calendar = Calendar.getInstance().apply {
            timeInMillis = now
            set(Calendar.HOUR_OF_DAY, 8)
            set(Calendar.MINUTE, 0)
            set(Calendar.SECOND, 0)
            set(Calendar.MILLISECOND, 0)
        }

        val startTime = calendar.timeInMillis

        calendar.set(Calendar.HOUR_OF_DAY, 21)
        val endTime = calendar.timeInMillis

        var currentTime = startTime

        while (currentTime <= endTime) {
            if (currentTime > now) { // 仅安排未来的任务
                val delay = currentTime - now
                val workRequest = OneTimeWorkRequestBuilder<DrinkPushWorker>()
                    .setInitialDelay(delay, TimeUnit.MILLISECONDS)
                    .build()
                WorkManager.getInstance(applicationContext).enqueue(workRequest)
            }
            currentTime += 2 * 60 * 60 * 1000 // 增加2小时
        }
    }
}